<script setup lang="ts">
import {supplierOpts} from "@/utils/status";
import {productFields} from "@/utils/field";
import {createProduct, getProductDetail, getProductOptions, ProductForm, SpecForm, updateProduct,} from "@/api/product";

defineOptions({
  name: "ProductEdit",
  inheritAttrs: false,
});

const steps = ref<String[]>(["基本信息", "规格信息"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  productId: {
    type: Number,
    default: null,
  },
});

const emit = defineEmits(["updateVisble", "close", "update:visible"]);
// 定义组件的事件
let {visible} = toRefs(props);

const objFormRef = ref(ElForm);
const loading = ref(false);
const stepActive = ref(0);
const modelFields = productFields();
const statusOptions = supplierOpts();
const spec_groups = reactive<SpecForm[]>([]);

const current_role = localStorage.getItem("role_name");
const shopList = ref<any[]>([]);

if (current_role != "sys") {
  modelFields[0].shop_id.hide = true;
}

/**
 * 初始化数据
 */
const originData = (): ProductForm => ({
  id: undefined,
  title: undefined,
  // sn: undefined,
  thumb: "",
  category_id: undefined,
  shop_id: undefined,
  stall_id: undefined,
  bag_price: undefined,
  price: undefined,
  cost_price: undefined,
  step: 0,
  status: 1,
  spec_type: 10,
  sort: 60,
  stock: undefined,
  weight: undefined,
  select_amount: 0,
  product_type: 0,
  content: undefined,
  product_feed: undefined,
  product_taste: undefined,
  min_buy: 1,
  is_single_seller: 0,
  limit_num: undefined,
});
const formData = reactive(originData());

watch(
  () => props.productId,
  (newVal) => {
    if (newVal) {
      loading.value = true;
      getProductDetail(newVal)
        .then(({data}) => {
          Object.assign(formData, data);

          if (formData["skus"]) {
            Object.assign(spec_groups, formData["skus"]);
          }
          /*modelFields[0].shop_id.options = shopList.value;
          if (formData["shop_id"]) {
            modelFields[0].shop_id.options.map((e1: any) => {
              if (e1.id == formData["shop_id"]) {
                modelFields[0].category_id.options = e1.categories || [];
                modelFields[0].stall_id.options = e1.stalls || [];
              }
            });
          }*/
          /*modelFields = productFields();
          if (current_role != "sys") {
          }
          if (formData.shop_id != "undefined") {
            modelFields[0].shop_id.disabled = true;
            modelFields[0].shop_id.options.map((e1: any) => {
              if (e1.id == formData.shop_id) {
                modelFields[0].category_id.disabled = true;
                modelFields[0].stall_id.disabled = true;

                modelFields[0].category_id.options = e1.categories || [];
                modelFields[0].stall_id.options = e1.stalls || [];
              }
            });
          }*/
          initForm();
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      initForm();
      resetForm();
    }
  }
);

function initForm() {
  // modelFields = productFields();
  modelFields[0].shop_id.options = shopList.value;

  if (current_role !== "sys") {
    modelFields[0].category_id.options = shopList.value[0].categories || [];
    modelFields[0].stall_id.options = shopList.value[0].stalls || [];

    if (!parseInt(String(formData.id || 0))) {
      formData.shop_id = shopList.value[0].id || "";
    }
  }

  if (formData.shop_id) {
    modelFields[0].shop_id.options.map((e1: any) => {
      if (e1.id == formData.shop_id) {
        modelFields[0].stall_id.options = e1.stalls || [];
        modelFields[0].category_id.options = e1.categories || [];
      }
    });
  }

  if (parseInt(String(formData.id || 0))) {
    modelFields[0].shop_id.disabled = true;
    modelFields[0].category_id.disabled = true;
    modelFields[0].stall_id.disabled = true;
  } else {
    modelFields[0].shop_id.disabled = false;
    modelFields[0].category_id.disabled = false;
    modelFields[0].stall_id.disabled = false;
  }
}

const rules = reactive([
  {
    title: [{required: true, message: "请输入名称", trigger: "blur"}],
    shop_id: [{required: true, message: "请选择所属店铺", trigger: "blur"}],
    stall_id: [{required: true, message: "请选择档口", trigger: "blur"}],
    category_id: [{required: true, message: "请选择分类", trigger: "blur"}],
    thumb: [{required: true, message: "请上传预览图", trigger: "blur"}],
    status: [{required: true, message: "请选择状态", trigger: "blur"}],
  },
  {
    price: [{required: true, message: "商品价格必填", trigger: "blur"}],
    stock: [{required: true, message: "库存必填", trigger: "blur"}],
  },
]);

function handleSubmit() {
  objFormRef.value.validate((valid: any) => {
    if (valid) {
      if (loading.value) {
        return;
      }
      const id = formData.id;
      formData.step = stepActive.value;
      if (stepActive.value == 1) {
        formData.skus = spec_groups;
      }
      loading.value = true;
      if (id) {
        updateProduct(id, formData)
          .then(() => {
            if (stepActive.value == 1) {
              stepActive.value = 0;
              closeDialog(1);
            } else {
              stepActive.value = 1;
            }
          })
          .finally(() => (loading.value = false));
      } else {
        createProduct(formData)
          .then((data) => {
            if (stepActive.value == 1) {
              stepActive.value = 0;
              closeDialog(1);
            } else {
              Object.assign(formData, data.data);
              stepActive.value = 1;
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

function closeDialog(type?: any) {
  resetForm();
  initForm();
  stepActive.value = 0;
  emit("close", type || 0);
}

function uploadSucess(res: any) {
  formData[res.name] = res.value || "";
}

function tabChanage(res: any) {
  stepActive.value = res || 0;
}

/*添加规格组*/
function addSpecGroup() {
  spec_groups.push({
    title: "",
    tagTitle: "",
    tagPrice: undefined,
    spec_items: [],
  });
}

//删除规格组
function deleteSpecGroup(idx?: any) {
  if (spec_groups[idx] != undefined) {
    if (spec_groups[idx].spec_items.length > 0) {
      ElMessage.error("请先删除规格值");
      return;
    }
    spec_groups.splice(idx, 1);
  }
}

/**
 * 删除规格值
 * @param specIdx
 * @param specVal
 */
function deleteSpecVal(specIdx: number, specValIdx: number) {
  if (
    spec_groups[specIdx] != undefined &&
    spec_groups[specIdx]!.spec_items[specValIdx] != undefined
  ) {
    spec_groups[specIdx]!.spec_items.splice(specValIdx, 1);
  }
}

// 添加规格值
function addSpecValue(idx?: any) {
  idx = idx || 0;
  if (spec_groups[idx] != undefined) {
    if (spec_groups[idx]!.title == "") {
      ElMessage.error("规格组名称必填");
      return;
    }
    if (spec_groups[idx]!.tagTitle == "") {
      ElMessage.error("规格值必填");
      return;
    }
    spec_groups[idx]!.spec_items.push({
      title: spec_groups[idx]!.tagTitle || "",
      price: spec_groups[idx]!.tagPrice || 0,
    });
    spec_groups[idx]!.tagTitle = "";
    spec_groups[idx]!.tagPrice = undefined;
  }
}

/**
 * 下拉款选择
 */
function handleSelect(fkey: any, value: any) {
  if (fkey == "shop_id") {
    modelFields[0].shop_id.options.map((e1: any) => {
      if (e1.id == value) {
        modelFields[0].category_id.options = e1.categories || [];
        modelFields[0].stall_id.options = e1.stalls || [];
        formData["stall_id"] = undefined;
        formData["category_id"] = undefined;
      }
    });
  }
}

/**
 * 初始化数据
 */
function initData() {
  stepActive.value = 0;

  getProductOptions()
    .then(({data}) => {
      loading.value = false;
      shopList.value = data.shops || [];

      /*if (current_role !== 'sys') {
        delete modelFields[0].shop_id;
        modelFields[0].category_id.options = shopList.value[0].categories || [];
        modelFields[0].stall_id.options = shopList.value[0].stalls || [];
        formData.shop_id = shopList.value[0].id || '';
      } else {
        modelFields[0].shop_id.options = shopList.value;
        if (formData.shop_id) {
          modelFields[0].shop_id.options.map((e1: any) => {
            if (e1.id == formData["shop_id"]) {
              modelFields[0].category_id.options = e1.categories || [];
              modelFields[0].stall_id.options = e1.stalls || [];
            }
          });
        }
      }*/
      initForm();
    })
    .finally(() => {
      loading.value = false;
    });
}

function resetForm() {
  objFormRef.value?.resetFields();
  objFormRef.value?.clearValidate();
  Object.assign(formData, originData());

  for (var i = 0; i <= spec_groups.length; i++) {
    spec_groups.splice(i, 1);
  }

  initForm();
}

onMounted(() => {
  initData();
});
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="productId ? '编辑商品' : '新增商品'"
    width="960px"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @close="closeDialog"
    custom-class="form-edit"
    v-loading="loading"
  >
    <el-tabs type="border-card" v-model="stepActive" @tab-change="tabChanage">
      <el-tab-pane :name="index" :label="item + ''" v-for="(item, index) in steps"/>
    </el-tabs>

    <el-form ref="objFormRef" :model="formData" :rules="rules[stepActive]" label-width="160px">
      <template v-for="(field, fk) in modelFields[stepActive]">
        <el-form-item
          :label="field.title"
          :prop="fk.toString()"
          :key="fk"
          v-if="
            !field.relateKey ||
            (field.relateKey && formData[field.relateKey] == field.relateVal)
          "
          :class="field.hide ? 'el-hide':''"
        >
          <div v-if="fk.toString() == 'skus'">
            <div class="spec-group" v-for="(spec, spindex) in spec_groups">
              <div class="spec-group-title">
                <el-input
                  v-model="spec.title"
                  class="spec-input"
                  placeholder="请输入规格组名称"
                />
                <el-button @click="deleteSpecGroup(spindex)" type="info" text
                >删除规格组
                </el-button
                >
              </div>

              <div class="spec-group-list">
                <div class="spec-group-item">
                  <el-input
                    v-model="spec.tagTitle"
                    class="spec-item-input"
                    placeholder="请输入规格值"
                  />
                  <el-input
                    type="number"
                    v-model="spec.tagPrice"
                    class="spec-item-input"
                    placeholder="请输入价格"
                    style="margin-right: 0px !important"
                  />
                  <el-button type="primary" link @click="addSpecValue(spindex)">新增规格值</el-button>
                </div>

                <div class="spec-group-tags margin10-t" v-if="spec.spec_items">
                  <el-tag
                    v-for="(tag, tidx) in spec.spec_items"
                    :key="tag.title"
                    closable
                    @close="deleteSpecVal(spindex, tidx)"
                    @click="deleteSpecVal(spindex, tidx)"
                    class="margin5-r"
                    type="primary"
                    style="cusor: poiner"
                  >
                    {{ tag.title }}
                    <template v-if="tag.price > 0"> / ￥ {{ tag.price }}</template>
                  </el-tag>
                </div>
              </div>
            </div>
            <el-button type="primary" size="default" @click="addSpecGroup">添加规格组</el-button>
          </div>
          <el-radio-group
            :disabled="field.disabled ? true : false"
            v-model="formData[fk]"
            v-else-if="field.type == 'radio'"
            :class="field.class || 'span2'"
          >
            <el-radio :label="Number(ok)" v-for="(op, ok) in field.options" :key="ok">{{ op }}</el-radio>
          </el-radio-group>
          <el-select
            :disabled="field.disabled ? true : false"
            v-model="formData[fk]"
            v-else-if="field.type == 'select'"
            :class="field.class || 'span2'"
            @change="handleSelect(fk.toString(), formData[fk])"
          >
            <el-option :label="op.title || ''" v-for="op in field.options" :value="Number(op.id)"
                       v-if="field.range_key"/>
            <el-option
              :label="op || ''"
              v-for="(op, ok) in field.options"
              :value="Number(ok)"
              v-else
            />
          </el-select>
          <single-upload
            :modelValue="formData[fk]"
            :fkey="String(fk)"
            @upload-sucess="uploadSucess"
            v-else-if="field.type == 'image'"
          />
          <el-time-picker v-model="formData[fk]" :value-format="field.format" is-range range-separator="至"
                          start-placeholder="起始时间" end-placeholder="结束时间" v-else-if="field.type == 'timerange'" class="timerange"/>
          <el-input
            :type="field.type || 'text'"
            v-model="formData[fk]"
            :maxlength="field.max || -1"
            :placeholder="'请输入' + field.title"
            :class="field.class || 'span2'"
            :disabled="field.disabled ? true : false"
            v-else
          />
        </el-form-item>
      </template>
      <div class="clear"></div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">{{
            stepActive == 1 ? "保存" : "下一步"
          }}
        </el-button>
        <el-button @click="closeDialog" type="default">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style>

.el-hide {
  display: none;
}

.el-range-editor.el-input__wrapper{flex: 0.4}

.spec-group {
  margin-bottom: 10px;
  background: #ecf5ff;
  padding: 10px;
}

.spec-group .el-button {
  padding: 10px 5px;
  font-size: 12px;
  margin-left: 10px !important;
}

.spec-group-title {
  margin-bottom: 10px;
}

.spec-group-title .spec-input {
  width: 76% !important;
}

.spec-group-item .spec-item-input {
  width: 37%;
  margin-right: 2% !important;
}

.spec-group-item .spec-item-input:last-child {
  margin-right: 0 !important;
}

.span2 {
  width: 40%;
}

.el-dialog__body {
  /*padding: 10px 20px !important;*/
  border: 1px solid #eee;
  margin: 0px 20px 30px !important;
}

.el-tabs--border-card {
  border: 0px !important;
}
</style>
